from flask import Flask, request, jsonify
from flask_cors import CORS
import uuid
from db import get_mysql_connection, get_redis_connection

app = Flask(__name__)
CORS(app)  # 允许所有跨域请求

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({"status": "error", "msg": "用户名或密码不能为空"}), 400

    conn = get_mysql_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
            if cursor.fetchone():
                return jsonify({"status": "error", "msg": "用户名已存在"})
            cursor.execute(
                "INSERT INTO users (username, password) VALUES (%s, %s)",
                (username, password)
            )
            conn.commit()
            return jsonify({"status": "success", "msg": "注册成功"})
    finally:
        conn.close()


@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({"status": "error", "msg": "用户名或密码不能为空"}), 400

    conn = get_mysql_connection()
    redis_conn = get_redis_connection()

    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM users WHERE username=%s AND password=%s"
            cursor.execute(sql, (username, password))
            user = cursor.fetchone()

            if user:
                token = str(uuid.uuid4())
                redis_conn.setex(f"user_token:{token}", 3600, username)
                return jsonify({"status": "success", "token": token})
            else:
                return jsonify({"status": "error", "msg": "用户名或密码错误"})
    finally:
        conn.close()


@app.route('/check', methods=['GET'])
def check_token():
    token = request.args.get('token')
    redis_conn = get_redis_connection()
    username = redis_conn.get(f"user_token:{token}")
    if username:
        return jsonify({"status": "success", "user": username.decode('utf-8')})
    else:
        return jsonify({"status": "error", "msg": "Token 无效或过期"}), 401


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
